package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.ProjectType;
import cn.stylefeng.guns.modular.business.enums.ProjectTypeExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.ProjectTypeMapper;
import cn.stylefeng.guns.modular.business.pojo.ProjectTypeRequest;
import cn.stylefeng.guns.modular.business.service.ProjectTypeService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业务实现层
 *
 * @author zhangyaowen
 * @date 2021/10/12 15:07
 */
@Service
public class ProjectTypeServiceImpl extends ServiceImpl<ProjectTypeMapper, ProjectType> implements ProjectTypeService {
    @Resource
    private LoginUserApi loginUserApi;
    @Resource
    private SubUseBrowseService subUseBrowseService;

	@Override
    public void add(ProjectTypeRequest projectTypeRequest) {
        ProjectType projectType = new ProjectType();
        BeanUtil.copyProperties(projectTypeRequest, projectType);
        this.save(projectType);
    }

    @Override
    public void del(ProjectTypeRequest projectTypeRequest) {
        ProjectType projectType = this.queryProjectType(projectTypeRequest);
        this.removeById(projectType.getId());
    }

    @Override
    public void edit(ProjectTypeRequest projectTypeRequest) {
        ProjectType projectType = this.queryProjectType(projectTypeRequest);
        BeanUtil.copyProperties(projectTypeRequest, projectType);
        this.updateById(projectType);
    }

    @Override
    public ProjectType detail(ProjectTypeRequest projectTypeRequest) {
        return this.queryProjectType(projectTypeRequest);
    }

    @Override
    public PageResult<Map<String, Object>> findPage(ProjectTypeRequest projectTypeRequest) {
        LambdaQueryWrapper<ProjectType> queryWrapper = new LambdaQueryWrapper<>();
        String hydraulicType = projectTypeRequest.getHydraulicType();
        queryWrapper.like(ObjectUtil.isNotEmpty(hydraulicType), ProjectType::getHydraulicType, hydraulicType);

        Page<ProjectType> sysRolePage = this.page(PageFactory.defaultPage(), queryWrapper);
        PageResult<ProjectType> projectTypePageResult= PageResultFactory.createPageResult(sysRolePage);
        List<ProjectType> list = projectTypePageResult.getRows();
        PageResult<Map<String, Object>> pageResult = new PageResult<>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(ProjectType projectType : list){
            Map<String, Object> map = new HashMap<String, Object>();
//            map = JSONObject.parseObject(JSONObject.toJSONString(projectType), Map.class);
//            map.remove("id");
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            String jmid = YunHeKey.YHGCLX+projectType.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            map.put("projectName",projectType.getProjectName());
            map.put("subdivideProject",projectType.getSubdivideProject());
            map.put("ptAnnalsfrom",projectType.getPtAnnalsfrom());
            mapList.add(map);
        }
        pageResult.setRows(mapList);
        pageResult.setPageNo(projectTypePageResult.getPageNo());
        pageResult.setTotalRows(projectTypePageResult.getTotalRows());
        pageResult.setPageSize(projectTypePageResult.getPageSize());
        pageResult.setTotalPage(projectTypePageResult.getTotalPage());
        return pageResult;
    }

    @Override
    public List<ProjectType> findList(ProjectTypeRequest projectTypeRequest) {
        LambdaQueryWrapper<ProjectType> wrapper = this.createWrapper(projectTypeRequest);
        return this.list(wrapper);
    }

    @Override
    public List<Map<String, Object>> findProjectType() {
        LambdaQueryWrapper<ProjectType> queryWrapper = new LambdaQueryWrapper<>();

        List<Map<String,Object>> mapList = new ArrayList<>();
        Map<String, Object> findMap = new HashMap<String, Object>();
        List<ProjectType> list= this.list(queryWrapper);

        List<String> projectList2 = list.stream().map(ProjectType::getHydraulicType).distinct().collect(Collectors.toList());
        for(String projectType : projectList2){
            Map<String, Object> map = new HashMap<String, Object>();
            if(projectType != ""){
                map.put("hydraulicType",projectType);
                mapList.add(map);
            }

        }

        return mapList;
    }


    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/10/12 15:07
     */
    private ProjectType queryProjectType(ProjectTypeRequest projectTypeRequest) {
        ProjectType projectType = this.getById(projectTypeRequest.getId());
        if (ObjectUtil.isEmpty(projectType)) {
            throw new ServiceException(ProjectTypeExceptionEnum.PROJECTTYPE_NOT_EXISTED);
        }
        return projectType;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/10/12 15:07
     */
    private LambdaQueryWrapper<ProjectType> createWrapper(ProjectTypeRequest projectTypeRequest) {
        LambdaQueryWrapper<ProjectType> queryWrapper = new LambdaQueryWrapper<>();

        Long id = projectTypeRequest.getId();
        String hydraulicType = projectTypeRequest.getHydraulicType();
        String projectName = projectTypeRequest.getProjectName();
        String subdivideProject = projectTypeRequest.getSubdivideProject();
        String projectIntroduce = projectTypeRequest.getProjectIntroduce();
        String quoteAnnotation = projectTypeRequest.getQuoteAnnotation();
        String ptAnnalsfrom = projectTypeRequest.getPtAnnalsfrom();
        String ptAnnalspage = projectTypeRequest.getPtAnnalspage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), ProjectType::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(hydraulicType), ProjectType::getHydraulicType, hydraulicType);
        queryWrapper.like(ObjectUtil.isNotEmpty(projectName), ProjectType::getProjectName, projectName);
        queryWrapper.like(ObjectUtil.isNotEmpty(subdivideProject), ProjectType::getSubdivideProject, subdivideProject);
        queryWrapper.like(ObjectUtil.isNotEmpty(projectIntroduce), ProjectType::getProjectIntroduce, projectIntroduce);
        queryWrapper.like(ObjectUtil.isNotEmpty(quoteAnnotation), ProjectType::getQuoteAnnotation, quoteAnnotation);
        queryWrapper.like(ObjectUtil.isNotEmpty(ptAnnalsfrom), ProjectType::getPtAnnalsfrom, ptAnnalsfrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(ptAnnalspage), ProjectType::getPtAnnalspage, ptAnnalspage);

        return queryWrapper;
    }

    @Override
    public List<Map<String, Object>> toReview(String jmId) {
        byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmId, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.YHGCLX,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {

            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(ProjectTypeExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<ProjectType> queryWrapper = new LambdaQueryWrapper<>();
        if ("".equals(id)) {
            List<Map<String, Object>> mapLists = new ArrayList<>();
//            Map<String, Object> map =new HashMap<>();
//            map.put("error","id为空");
            return mapLists;
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), ProjectType::getId, id);
        List<ProjectType> projectTypeList = this.list(queryWrapper);
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.GONGCHENGKJ,projectTypeList.get(0).getPtTitle(),userid,request);
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (ProjectType projectType : projectTypeList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(projectType), Map.class);

            // 获取类的属性
            Field[] declaredFields = ProjectType.class.getDeclaredFields();
            List<Map<String, Object>> mplist = new ArrayList<>();
            // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
            if (declaredFields.length != 0) {
                int i = 1;
                Map<String, Object> p = new HashMap<String, Object>();
                for (Field field : declaredFields) {

                    Map<String, Object> mp = new HashMap<String, Object>();
                    if (field.getAnnotation(ApiModelProperty.class) != null) {
                        //获取注解属性
                        ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                        // key和value可根据需求存
                        // 这存的key为注解的值，value为类属性名

                        if("ptTitle".equals(field.getName()) || "projectIntroduce".equals(field.getName())  ) {
                            if("ptTitle".equals(field.getName())){
                                p.put("title", map.get(field.getName()));
                            }else {
                                p.put(field.getName(), map.get(field.getName()));
                            }
                        }else{
                            mp.put("key", aa.value());
                            mp.put("value", map.get(field.getName()));

                            if (i != 1) {
                                mplist.add(mp);
                            }
                        }

                    }
                    i++;
                }
                p.put("list", mplist);
                if (i != 1) {
                    mapList.add(p);
                }
            }
        }
        return mapList;
    }
}